package za.org.jcicada.comms.impl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import za.org.jcicada.comms.IMessageSerializerStrategy;
import za.org.jcicada.comms.messages.CommsMessage;

public class JavaMessageSerializer implements IMessageSerializerStrategy {

	@Override
    public byte[] toBytes(CommsMessage msg) throws IOException {
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(byteOut) ;
        out.writeObject(msg);
        out.close();
        return byteOut.toByteArray();
    }

	@Override
    public CommsMessage fromBytes(byte[] bytes) throws IOException {
        try {
            ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
            CommsMessage msg = (CommsMessage) in.readObject();
            in.close();
            return msg;
        } catch (ClassNotFoundException ex) {
            throw new IOException("Failed to deserialize message (unknown class)", ex);
        }
    }

}
